package com.lgc.common.base

import androidx.lifecycle.MutableLiveData
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Job
import kotlinx.coroutines.launch

abstract class BaseViewModel :ViewModel() {
    private val jobs= mutableListOf<Job>()
    val isLoading= MutableLiveData<Boolean>()//标记网络loading状态

    /**
     * 协程封装,网络请求
     */
    fun serverAwait(block:suspend CoroutineScope.()->Unit)=viewModelScope.launch {
        isLoading.value=true
        block.invoke(this)
        isLoading.value=false
    }.addto(jobs)

    /**
     * 扩展函数,用于viewmodel中的Job添加到list列表中
     */
  private fun Job.addto(list:MutableList<Job>){
      list.add(this)
  }
}